<template>
    <div>
        <!-- 导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 添加商品信息警告栏 -->
         <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>

         <!-- 添加商品信息步骤条 -->
        <el-steps :active="activeIndex - 0" align-center>
          <el-step title="基本信息" ></el-step> 
          <el-step title="商品参数" ></el-step>
          <el-step title="商品属性" ></el-step>
          <el-step title="商品图片" ></el-step>
          <el-step title="商品内容" ></el-step>
          <el-step title="完成" ></el-step>
        </el-steps>


        <!-- 左侧步骤条外面的Form -->
        <el-form :model="addForm" :rules="addRules" ref="addFormref" label-width="100px" label-position="top">
                <!-- 添加商品步骤条左侧区域 -->
                <el-tabs :tab-position="tabPosition" v-model="activeIndex" :before-leave="beforeleave"
                  @tab-click="tabClick">

                <el-tab-pane label="基本信息" name="0">
                         <el-form-item label="商品名称" prop="goods_name">
                           <el-input v-model="addForm.goods_name"></el-input>
                         </el-form-item>

                          <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price"></el-input>
                          </el-form-item>

                           <el-form-item label="商品重量" prop="goods_weight">
                             <el-input v-model="addForm.goods_weight"></el-input>
                           </el-form-item>

                           <el-form-item label="商品数量" prop="goods_number">
                             <el-input v-model="addForm.goods_number"></el-input>
                           </el-form-item>

                            <el-form-item label="商品分类" prop="goods_cat">
                            <!-- 级联选择器 -->
                             <!-- :options 是用来指明数据源的 -->
                             <!-- props是用来配置节点选择框的后面那些数据 valus label children -->
                             <!-- v-model可以把咱们选定的那些id值双向绑定到数据中 -->
                             <!-- change选择项改变的事项 -->
                              <el-cascader v-model="addForm.goods_cat" :options="getAddShop"
                                expandTrigger='hover' :props="cateprops"  @change="handleChange"></el-cascader>
                            </el-form-item>

                </el-tab-pane>

                <el-tab-pane label="商品参数" name="1">
                      <!-- 渲染表单的item表单项 -->
                      <el-form-item
                      v-for="item in manyTabList"
                      :key="item.attr_id"
                      :label="item.attr_name">
                        <el-checkbox-group v-model="item.attr_vals">
                          <el-checkbox border v-for="(cb, i) in item.attr_vals" :key="i" :label="cb" >
                          </el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="商品属性" name="2">
                  <!-- 渲染表单的item表单项 -->
                  <!-- v-for 指令需要使用 item in items 形式的特殊语法，其中 items 是源数据数组，而 item 则是被迭代的数组元素的别名。 -->
                   <el-form-item
                   v-for="item in onlyTabList"
                   :key = "item.attr_id"
                   :label="item.attr_name">
                     <el-input v-model="item.attr_vals"></el-input>
                   </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="商品图片" name="3">
                  <!-- action 表示图片上传到的api -->
                  <!-- list-type 可以指定图片的预览方式 -->
                    <el-upload :action="uploadURL"
                      :on-preview="handlePreview" :on-remove="handleRemove"  list-type="picture" :headers= "headerObj" :on-success="handleSuccess">
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-tab-pane>
                
                <el-tab-pane label="商品内容" name="4">
                      <!-- 富文本编辑器 -->
                      <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" >
                      </quill-editor>
                      <el-button type="primary" class="btnsquill" @click="add">添加商品</el-button>
                </el-tab-pane>

                </el-tabs>

                <!-- 预览窗口 -->
                <el-dialog title="预览图片" :visible.sync="previewDialogVisible" width="50%">
                  <img :src="previewurl" alt="">
                </el-dialog>
        </el-form>
    </div>
</template>

<script>

import _ from 'lodash'

export default {
    data(){
        return {
            // 添加商品步骤条左侧区域
             tabPosition: 'left',
             activeIndex: "0",
             getAddShop:[],
            //  动态属性列表
             manyTabList:[],
            // 静态属性列表
            onlyTabList:[],
            // 图片上传路径
            uploadURL:'http://39.106.78.41:8888/api/private/v1/upload',
            // 图片上传组件headers请求头
             headerObj: {
             Authorization:window.sessionStorage.getItem('token')
             },
              previewurl:'',
             addForm:{
                goods_name: '',
                goods_price: 0,
                goods_weight: 0,
                goods_number: 0,
                // 商品所属的分类数组
                goods_cat:[],
                // 图片上传的数组
                pics:[],
                goods_introduce:'',
                attrs:[]
             },
             addRules:{
                  goods_name:[
                  { required: true, message: '请输入商品名称', trigger: 'blur' },
                  { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                  ],
                  goods_price: [
                  { required: true, message: '请输入商品价格', trigger: 'blur' }
                  ],
                  goods_weight:[
                  { required: true, message: '请输入商品重量', trigger: 'blur' }
                  ],
                  goods_number:[
                  { required: true, message: '请输入商品数量', trigger: 'blur' }
                  ],
                  goods_cat:[
                  { required: true, message: '请输入商品分类', trigger: 'blur' }
                  ]
             },
             cateprops:{
                 value:'cat_id',
                 label:'cat_name',
                 children:'children'
             },

             previewDialogVisible: false,
             
             
        }
    },


    created(){
        this.getAddgoods()
    },


    methods:{
       async getAddgoods(){
          const {data: res}  = await this.$http.get('categories')

          if(res.meta.status !== 200){
              return this.$message.error('获取商品失败')
          }
            this.$message.success('获取商品成功')


              this.getAddShop = res.data
              // console.log(this.getAddShop);
        },

        // 只能选择第三个级联框
        handleChange(){
            if(this.addForm.goods_cat.length !== 3){
                this.addForm.goods_cat = []
            }
        },
      
        beforeleave(activeName, oldActiveName){
          if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
            this.$message.error('请先选择商品分类')
            return false
          }
        },

       async tabClick(){
           if(this.activeIndex === '1'){
         const{data:res} = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`,{params: {
            sel: 'many'
          }})

          if(res.meta.status !== 200){
             return this.$message.error('获取参数列表失败')
          }

        // 把参数循环得到
          res.data.forEach(item => {
           item.attr_vals =  item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          })

              this.manyTabList = res.data
              console.log(this.manyTabList);

          }else if(this.activeIndex === '2'){
              const{data:res} = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`,{params: { sel: 'only'
            }})

             if(res.meta.status !== 200){
             return this.$message.error('获取参数列表失败')
             }
             this.onlyTabList = res.data
             console.log(this.onlyTabList);
          }
        },

        // 处理预览图片效果
        handlePreview(file){
          console.log(file);
          // 获取图片的url
          this.previewurl = file.response.data.url
          this.previewDialogVisible = true
        },
      
        // 处理移出图片的操作
        handleRemove(file){
        //  1、获取将要删除的图片的临时路径
        const filePath = file.response.data.tmp_path
        //  2、从pics 数组中，找出这个图片对应的索引值
        const i = this.addForm.pics.findIndex(x => x.pic === filePath )
        //  3、调用数组的splice 方法，把图片信息对象，从pics 数组中移出
        this.addForm.pics.splice(i, 1)
          // console.log(file);
          console.log(this.addForm);
        },

        // 监听图片的上传成功的事件
        handleSuccess(response){
          // console.log(response);
          // 拼接得到一个图片信息对象
          const picInfo = {pic: response.data.tmp_path}
          // 将信息图片对象 push 到 pice 数组中
          this.addForm.pics.push(picInfo)
        },

        // 富文本添加商品按钮
        add(){
          this.$refs.addFormref.validate(async valid => {
            if (!valid){
            return this.$message.error('请填写必要的表单项')
          }
          
          // // 执行添加的业务逻辑
          // // lodash cloneDeep(obj)
          const form = _.cloneDeep(this.addForm)
          form.goods_cat =
          form.goods_cat.join(',')
          // console.log(form);
          // 处理动态参数
          this.manyTabList.forEach(item => {
            const newInfo = {attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')}
            this.addForm.attrs.push(newInfo)
          })
          // 处理静态属性
          this.onlyTabList.forEach(item => {
            const newInfo = {attr_id: item.attr_id,
            attr_value: item.attr_vals}
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          console.log(form);


          // 发起请求添加商品
          // 商品的名称唯一 

        const {data: res} = await this.$http.post('goods', form)

        if(res.meta.status !== 201){
          return this.$message.error('添加商品失败')
        }
            this.$message.success('添加商品成功')
            this.$router.push('/goods')
          })
        }
    }
}
</script>


<style lang="less" scoped>
    .el-steps {
        margin-top: 15px;
    }

    .el-tabs {
        margin-top: 20px;
    }

    .btnsquill {
      margin-top: 15px;
    }
</style>